package com.example.mediaservice.websocket;

import org.springframework.stereotype.Controller;
import javax.websocket.*;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.CopyOnWriteArraySet;

@Controller
@ServerEndpoint("/audio")
public class ReceiveAudio {
    public static final CopyOnWriteArraySet<ReceiveAudio> receAudioSessions = new CopyOnWriteArraySet<>();
    public Session session;

    @OnOpen
    public void onOpen(Session session) throws IOException {
        System.out.println("onOpen");
        this.session = session;
        receAudioSessions.add(this);
    }

    @OnClose
    public void onClose() throws IOException {
        System.out.println("onClose");
        receAudioSessions.remove(this);
        this.session.close();
    }

    @OnMessage
    public void onMessage(byte[] pcmData, Session session) throws IOException {
        Object[] arr = SendAudio.sendAudioSessions.toArray();
        ByteBuffer byteBuffer=ByteBuffer.allocate(pcmData.length);
        byteBuffer.put(pcmData);
        byteBuffer.flip();
        System.out.println(arr.length+" : "+byteBuffer.capacity());
        for(Object _item:arr) {
            SendAudio item = (SendAudio) _item;
            item.sendMessage(byteBuffer);
            System.out.println("sendMessage => end : " + arr.length + " , " + byteBuffer.capacity());
        }
    }

    @OnError
    public void onError(Session session, Throwable error) throws IOException {
        System.out.println("onError");
        error.printStackTrace();
        receAudioSessions.remove(this);
        session.close();
    }
}
